package com.yang.common.advice;

import com.yang.common.exception.BusinessException;
import com.yang.common.utils.MdcUtil;
import com.yang.model.common.dtos.ResponseResult;
import com.yang.model.common.dtos.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: Billyang
 * @date: 2024/9/17 22:55
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult<?> error(Exception e, HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        log.error("未知异常:", e);
        sendErrorIfPage(request, response, handler);
        return ResponseResult.errorResult(ResultCode.SYSTEM_ERROR).setTraceId(MdcUtil.get());
    }

    /**
     * 拦截未处理的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult<?> runtime(RuntimeException e, HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        log.error("未处理运行时异常", e);
        sendErrorIfPage(request, response, handler);
        return ResponseResult.errorResult(ResultCode.SYSTEM_ERROR).setTraceId(MdcUtil.get());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult<?> business(BusinessException e, HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        String message = e.getMessage();
        if (StringUtils.isBlank(message)) {
            message = ExceptionUtils.getStackTrace(e);
        }
        log.warn("业务异常:{}", message);
        sendErrorIfPage(request, response, handler);
        return ResponseResult.errorResult(e.getCode(), e.getMessage());
    }

    private boolean isReturnJson(HandlerMethod handler) {
        if (handler.getBeanType().isAnnotationPresent(RestController.class)) {
            return true;
        }
        Method method = handler.getMethod();
        if (method.isAnnotationPresent(ResponseBody.class)) {
            return true;
        }
        return false;
    }

    private void sendErrorIfPage(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        String accept = request.getHeader("Accept");
        if (StringUtils.isNotBlank(accept) && accept.contains("application/json")) {
            return;
        }
        String contentType = response.getContentType();
        if (StringUtils.isNotBlank(contentType) && contentType.contains("application/json")) {
            return;
        }
        if (isReturnJson(handler)) {
            return;
        }
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("sendError error", e);
        }
    }

}
